package cn.sms.org.service.impl;

import cn.sms.basic.service.impl.BaseServiceImpl;
import cn.sms.basic.util.MD5Utils;
import cn.sms.basic.util.StrUtils;
import cn.sms.org.domain.Employee;
import cn.sms.org.mapper.EmployeeMapper;
import cn.sms.org.service.IEmployeeService;
import cn.sms.user.domain.Logininfo;
import cn.sms.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void add(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo= employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }
    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); //0 是员工 1 用户
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String securityPwd = MD5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(securityPwd);
    }

    @Override
    public Employee ByLogininfoId(Long id) {
        return employeeMapper.ByLogininfoId(id);
    }
}
